using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Windows.Browser;
using System.Windows.Documents;
using com.bodurov.SilverlightControls.XmlCodeEditor.Extensions;

namespace com.bodurov.SilverlightControls.XmlCodeEditor.Utils
{
    public static class Dbg
    {
        private static bool _isInitialized;
        private static bool _canTrace;
        public static bool IsVerboseTrace;

        public static void Trace(string msg, params object[] args)
        {
            if (!_isInitialized) Initialize();
            if (!_canTrace) return;
            if (msg == null) return;
            var str = args.Length == 0 ? msg : String.Format(msg, args);
            HtmlPage.Window.Invoke("__DoTrace", str);
        }

        public static void Trace(TextPointer pointer)
        {
            if (!_isInitialized) Initialize();
            if (!_canTrace) return;
            Trace(pointer == null ? "NULL" : pointer.GetDescription());
        }

        private static void Initialize()
        {
            _isInitialized = true;

            var traceFunc = HtmlPage.Window.Eval("typeof __DoTrace");
            if (traceFunc == null || traceFunc.ToString() == "undefined")
            {
                return;
            }

            _canTrace = true;
        }

        public static void TraceForEach<T>(IEnumerable<T> parts, Func<T, int, string> func)
        {
            var sb = new StringBuilder();
            var i = 0;
            foreach (var each in parts)
            {
                var str = func(each, i++);
                sb.Append(str);
            }
            Debug.WriteLine(sb.ToString());
            //HtmlPage.Window.Invoke("__DoTrace", sb.ToString());
        }
    }
}